package com.example.demo.test1.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.config.ApplicationConfiguration;
import com.example.demo.test1.entity.AccountViewDTO;
import com.example.demo.test1.entity.Test1;
import com.example.demo.test1.entity.UsernamePasswordSmsCredential;
import com.example.demo.test1.mapper.ITest1Mapper;
import com.example.demo.test1.service.AccountService;
import com.example.demo.test1.service.ITest1Service;
import com.example.demo.utils.CustomThreadPoolExecutor;
import com.example.demo.utils.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.util.unit.DataSize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;

@RestController
@RequestMapping("/test1/")
@Api(tags = "测试 apis")
public class Test1Controller {

    @Autowired
    private ITest1Service test1Service;
    @Autowired
    private ITest1Mapper test1Mapper;
    @Resource
    private ApplicationConfiguration configuration;
    @Autowired
    private AccountService accountService;

    @GetMapping("getList")
    @ApiOperation("分页获取所有数据")
    public Page<Test1> getList(@ApiParam("当前页数") int current, @ApiParam("每页显示几条数据")int pageSize){
        Page<Test1> page = new Page<>(current, pageSize);
        Page<Test1> list = test1Service.getList(page);
        return list;
    }

    @GetMapping("500/{flag}")
    @ApiOperation("分页获取所有数据")
    public ResponseData<Page<Test1>> get500(@PathVariable Boolean flag){
        if (flag){
            throw new RuntimeException( "500错误！");
        } else {
            return ResponseData.success(new Page<>());
        }

    }

    @GetMapping("setList")
    @ApiOperation("保存或更新数据")
    public Boolean setList(){
        Test1 test1 = new Test1();
//        test1.setId(7);
        test1.setFirst("7");
        test1.setSecond("7");
        test1.setCreateTime(new Date());
        test1Service.save(test1);
        return true;
    }

    @PutMapping("test")
    @ApiOperation("保存或更新数据")
    public Boolean test(@RequestBody UsernamePasswordSmsCredential credential){
        System.out.println(credential.toString());
        return true;
    }

    @PostMapping("test")
    @ApiOperation("保存或更新数据")
    public Boolean test223(UsernamePasswordSmsCredential credential){
        System.out.println(credential.toString());
        return true;
    }


    @GetMapping("testIn")
    @ApiOperation("保存或更新数据")
    public Boolean testIn(){
        Integer[] ids = new Integer[]{1, 2, 3};
        List<Test1> byIds = test1Mapper.getByIds(ids);
        System.out.println(byIds);
        return true;
    }

    @PostMapping("upload")
    @ApiOperation("上传附件")
    public String upload(MultipartFile file) throws IOException {
        //判断是否有文件上传
        if(file == null) {
            return "请重新上传附件！";
        }
        if (file.getSize() > DataSize.parse(configuration.getMaxFileSize()).toBytes()){
            return "文件过大！";
        }
        String path = configuration.getEnclosureSavePath();
        // 判断文件夹是否存在
        File directory = new File(path);
        if (!directory.exists()) {
            directory.mkdir();
        }
        String oldFilename = file.getOriginalFilename();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = oldFilename.replace(".","-"+dateFormat.format(new Date())+"." ) ;
        File localFile = new File(path + fileName);
        try {
            file.transferTo(localFile); //将上传文件写到服务器上指定的文件
            // 保存到数据库
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "图片上传失败，请重新上传！";
        }
    }

    @GetMapping("upload")
    @ApiOperation("下载附件")
    public String upload(String fileName, HttpServletResponse response) throws IOException {
        if(fileName == null){
            return "文件名称不能为空！";
        }
        String path = configuration.getEnclosureSavePath() + fileName;
        File file = new File(path);
        if(file.exists()){ //判断文件是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(fileName,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("----------file download---" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @GetMapping("rock")
    @ApiOperation("回滚")
    public String rock(String a){
        test1Service.rock(a);
        return "aaaa";
    }

    @GetMapping("export/check/{year}/{groupId}")
    @ApiOperation("导出账单-检查")
    public ResponseData exportCheckResourceAccountExcelByYear(@PathVariable Integer year, @PathVariable String groupId) {
        boolean res = accountService.exportCheckAccountExcelByYear(year, groupId);
        if (res) {
            return ResponseData.success();
        } else {
            return ResponseData.failure("暂无数据");
        }
    }

    @GetMapping("export/{year}/{groupId}")
    @ApiOperation("导出账单-导出")
    public void exportResourceAccountExcelByYear(@PathVariable Integer year, @PathVariable String groupId, HttpServletResponse response) {
        accountService.exportAccountExcelByYear(year, groupId, response);
    }

    @GetMapping("view/month/type/{year}/{groupId}")
    @ApiOperation("获取账单页面展示内容-月类型趋势")
    public ResponseData<AccountViewDTO> getAccountMonthTypeView(@PathVariable Integer year, @PathVariable String groupId) {
        return ResponseData.success(accountService.getAccountMonthTypeView(year, groupId));
    }


    @GetMapping("testShutdown")
    @ApiOperation("回滚")
    public String testShutdown(String a){
        CustomThreadPoolExecutor exec = new CustomThreadPoolExecutor();
        //1. 初始化
        exec.init();
        ExecutorService pool = exec.getCustomThreadPoolExecutor();
        pool.execute(() -> {
            try {
                Thread.sleep(10*1000);
                System.out.println(0000000000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        //停止线程池，该过程不再继续接受新任务了，但是还是会等待以前提交的任务执行完才关闭
        pool.shutdown();
        System.out.println(1111111111);
        return "aaaa";
    }

}
